package com.example.administrator.myjdlc.utils;

/**
 * Created by Administrator on 2017/3/21.
 */

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Looper;
import android.telephony.TelephonyManager;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.Toast;

import com.example.administrator.myjdlc.AppApplication;
import com.example.administrator.myjdlc.db.DBBack;
import com.example.administrator.myjdlc.db.DBInterface;
import com.example.administrator.myjdlc.db.DBUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CommonUtils {
    static boolean checkTime = false;
    static boolean result = false;
    public static final int LOGIN_TIME = 3;
//    static DialogRemindUi remind;

    public CommonUtils() {
    }

    public static boolean isRegexPhone(String strPhone) {
        if(strPhone == null) {
            return false;
        } else {
            Pattern p = Pattern.compile("^((13[0-9])|(14[0-9])|(15[^4,\\D])|(17[0-9])|(18[0-9]))\\d{8}$");
            Matcher m = p.matcher(strPhone);
            return m.matches();
        }
    }

    public static boolean isEmail(String email) {
        String str = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
        Pattern p = Pattern.compile(str);
        Matcher m = p.matcher(email);
        return m.matches();
    }

    public static boolean isCorrectPwd(String pwd) {
        if(pwd == null) {
            return false;
        } else {
            Pattern p = Pattern.compile("[0-9]*");
            Matcher m = p.matcher(pwd);
            return !pwd.equals("") && pwd.length() == 6 && m.matches();
        }
    }

    public static boolean isChinese(String name) {
        if(name != null && !name.equals("") && name.length() >= 1) {
            String pstr = "^[一-龥豈-鶴]+$";
            Pattern p = Pattern.compile(pstr);
            Matcher m = p.matcher(name);
            return m.matches();
        } else {
            return false;
        }
    }

    public static boolean checkBankCard(String cardId) {
        char bit = getBankCardCheckCode(cardId.substring(0, cardId.length() - 1));
        return bit == 78?false:cardId.charAt(cardId.length() - 1) == bit;
    }

    private static char getBankCardCheckCode(String nonCheckCodeCardId) {
        if(nonCheckCodeCardId != null && nonCheckCodeCardId.trim().length() != 0 && nonCheckCodeCardId.matches("\\d+")) {
            char[] chs = nonCheckCodeCardId.trim().toCharArray();
            int luhmSum = 0;
            int i = chs.length - 1;

            for(int j = 0; i >= 0; ++j) {
                int k = chs[i] - 48;
                if(j % 2 == 0) {
                    k *= 2;
                    k = k / 10 + k % 10;
                }

                luhmSum += k;
                --i;
            }

            return luhmSum % 10 == 0?'0':(char)(10 - luhmSum % 10 + 48);
        } else {
            return 'N';
        }
    }

    public static int getAPNType(Context context) {
        byte netType = 0;
        ConnectivityManager connMgr = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if(networkInfo == null) {
            return netType;
        } else {
            int nType = networkInfo.getType();
            if(nType == 1) {
                netType = 1;
            } else if(nType == 0) {
                int nSubType = networkInfo.getSubtype();
                TelephonyManager mTelephony = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
                if(nSubType == 3 && !mTelephony.isNetworkRoaming()) {
                    netType = 2;
                } else {
                    netType = 3;
                }
            }

            return netType;
        }
    }

    public static String md5(String s) {
        Object result = null;

        try {
            MessageDigest e = MessageDigest.getInstance("MD5");
            e.update(s.getBytes());
            byte[] messageDigest = e.digest();
            StringBuffer hexString = new StringBuffer();

            for(int i = 0; i < messageDigest.length; ++i) {
                String h;
                for(h = Integer.toHexString(255 & messageDigest[i]); h.length() < 2; h = "0" + h) {
                    ;
                }

                hexString.append(h);
            }

            return hexString.toString();
        } catch (NoSuchAlgorithmException var7) {
            var7.printStackTrace();
            return (String)result;
        }
    }

    public static int getAPNType() {
        byte netType = 0;
        ConnectivityManager connMgr = (ConnectivityManager) AppApplication.getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if(networkInfo == null) {
            return netType;
        } else {
            int nType = networkInfo.getType();
            if(nType == 1) {
                netType = 1;
            } else if(nType == 0) {
                int nSubType = networkInfo.getSubtype();
                TelephonyManager mTelephony = (TelephonyManager) AppApplication.getContext().getSystemService(Context.TELEPHONY_SERVICE);
                if(nSubType == 3 && !mTelephony.isNetworkRoaming()) {
                    netType = 2;
                } else {
                    netType = 3;
                }
            }

            return netType;
        }
    }

    public static void showhideInput(Context context) {
        InputMethodManager imm = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, 2);
    }

    public static String getSubString(String str) {
        return str.length() > 4?str.substring(str.length() - 4, str.length()):"";
    }

    public static String getTransString(String str) {
        if(str.length() > 5) {
            try {
                String e = str.substring(str.length() - 5, str.length());
                String[] split = e.split("-");
                return split[0] + "." + split[1];
            } catch (Exception var3) {
                return str;
            }
        } else {
            return str;
        }
    }

    public static String getDeletYearString(String str) {
        if(str.length() > 5) {
            try {
                String e = str.substring(5, str.length());
                return e;
            } catch (Exception var2) {
                return str;
            }
        } else {
            return str;
        }
    }

    @SuppressLint({"SimpleDateFormat"})
    public static String getTimeStr() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        Date curDate = new Date(System.currentTimeMillis());
        return formatter.format(curDate);
    }

    public static boolean isNum(String str) {
        return str != null && !str.equals("")?str.matches("^[-+]?(([0-9]+)([.]([0-9]+))?|([.]([0-9]+))?)$"):false;
    }

    public static int getRandomNumber() {
        return (int)((Math.random() * 9.0D + 1.0D) * 100000.0D);
    }

    public static String getRiskType(int key) {
        return key == 1?"安全":(key == 2?"保守":(key == 3?"稳健":(key == 4?"积极":(key == 5?"进取":"未知"))));
    }

    public static int getOrderRisk(String str) {
        int key = Integer.valueOf(str).intValue();
        return key == 0?1:(key == 1?3:(key == 2?5:(key == 3?4:(key == 4?2:-1))));
    }

    public static String createFileName() {
        return md5("com.jzkj.manage" + System.currentTimeMillis());
    }

/*    public static String getRsaStr(String parameter) {
        try {
            RSAUtil e = RSAUtil.getInstance();
            parameter = e.encrypt(parameter.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException var2) {
            var2.printStackTrace();
        } catch (Exception var3) {
            var3.printStackTrace();
        }

        return parameter;
    }*/

    @SuppressLint({"NewApi"})
/*    public static boolean isLogined() {
        return !TextUtils.isEmpty((String) SPUtils.get("com.jzkj.manage.login", ""));
    }*/

    /*public static void addTime() {
        ContentValues cv = new ContentValues();
        if(checkTime()) {
            cv.put("receptionTime", String.valueOf(System.currentTimeMillis()));
           DBUtils.getInstance().updateData("time", cv, "id=?", new String[]{"1"}, (DBInterface)null);
        } else {
            cv.put("receptionTime", String.valueOf(System.currentTimeMillis()));
           DBUtils.getInstance().addData("time", cv, (DBInterface)null);
        }

    }*/

    public static void addTimeOne() {
        ContentValues cv = new ContentValues();
        if(checkTime()) {
            cv.put("receptionTime", "0");
           DBUtils.getInstance().updateData("time", cv, "id=?", new String[]{"1"}, (DBInterface)null);
        } else {
            cv.put("receptionTime", "0");
           DBUtils.getInstance().addData("time", cv, (DBInterface)null);
        }

    }

    public static boolean checkTime() {
       DBUtils util =DBUtils.getInstance();
        DBInterface dBInterface = new DBInterface() {
            public void dBListener(DBBack data) {
                if(data.getEventCode() == 5) {
                    Cursor c = (Cursor)data.getObj();
                    if(c == null) {
                        CommonUtils.checkTime = false;
                    } else {
                        if(c.getCount() == 0) {
                            CommonUtils.checkTime = false;
                        } else {
                            CommonUtils.checkTime = true;
                        }

                        c.close();
                    }
                }

            }
        };
        util.queryData("time", "id=?", new String[]{"1"}, (String)null, (String)null, dBInterface);
        return checkTime;
    }

/*    public static boolean isNeedLogin() {
        result = false;
       DBUtils util =DBUtils.getInstance();
        DBInterface dBInterface = new DBInterface() {
            public void dBListener(DBBack data) {
                if(data.getEventCode() == 5) {
                    Cursor c = (Cursor)data.getObj();
                    if(c == null) {
                        CommonUtils.addTime();
                        CommonUtils.result = true;
                    } else {
                        if(c.getCount() == 0) {
                            CommonUtils.result = true;
                            CommonUtils.addTime();
                        } else {
                            String time;
                            for(time = ""; c != null && c.moveToNext(); time = c.getString(1)) {
                                ;
                            }

                            CommonUtils.result = CommonUtils.judgmentTime(time);
                            CommonUtils.addTime();
                        }

                        c.close();
                    }
                }

            }
        };
        util.queryData("time", "id=?", new String[]{"1"}, (String)null, (String)null, dBInterface);
        return result;
    }*/

    private static boolean judgmentTime(String time) {
        if(time.equals("0")) {
            return false;
        } else {
            long nowTime = System.currentTimeMillis() / 60000L;
            long previousTime = Long.parseLong(time) / 60000L;
            return nowTime - previousTime >= 3L;
        }
    }

    public static String getCodeMessage(int code) {
        String result = "";
        if(code == 9999) {
            result = "Internal server error";
        } else if(code == 1000) {
            result = "缺少参数";
        } else if(code == 1001) {
            result = "参数无效";
        } else if(code == 1002) {
            result = "签名无效";
        } else if(code == 1003) {
            result = "请求已失效";
        } else if(code == 1004) {
            result = "用户名密码错误";
        } else if(code == 1005) {
            result = "密码错误";
        } else if(code == 1006) {
            result = "会话令牌已失效，请重新登录";
        } else if(code == 1007) {
            result = "业务处理失败";
        } else if(code == 1008) {
            result = "验证码错误";
        } else if(code == 1009) {
            result = "直销系统返回数据有误";
        } else if(code == 1010) {
            result = "验证码发送失败";
        } else if(code == 1011) {
            result = "直销系统业务异常（含直销返回的异常信息）";
        } else if(code == 1012) {
            result = "开户信息校验失败";
        } else if(code == 1013) {
            result = "开户失败";
        } else if(code == 1014) {
            result = "该手机号已经注册";
        } else if(code == 1015) {
            result = "Email格式不正确";
        } else if(code == 1016) {
            result = "密码格式不正确，请输入6位数字的密码";
        } else if(code == 1017) {
            result = "用户名格式不正确";
        }

        return result;
    }

/*    public static void checkLoginStatus(com.jzkj.manage.net.NetLoadListener listener) {
        com.jzkj.manage.net.NetService netService = com.jzkj.manage.net.NetService.getInstance();
        netService.clearParams();
        netService.setHttpMethod("GET");
        netService.setUrl("https://106.39.107.101/account/info");
        netService.loader(listener);
    }*/

 /*   public static void showCustom(final Context context) {
        View.OnClickListener cancel = null;
        View.OnClickListener confirmClick = new View.OnClickListener() {
            public void onClick(View v) {
                Intent intent = new Intent("android.intent.action.CALL", Uri.parse("tel:4000200018"));
                context.startActivity(intent);
                CommonUtils.remind.dismiss();
            }
        };
        cancel = new View.OnClickListener() {
            public void onClick(View v) {
                CommonUtils.remind.dismiss();
                context.startActivity(new Intent(context, LoginActivity.class));
            }
        };
        remind = new DialogRemindUi(context, confirmClick, cancel);
        remind.setConfirmTxt(AppApplication.getContext().getString(R.string.call));
        remind.setCancelTxt(AppApplication.getContext().getString(R.string.cancel));
        remind.setCanceledOnTouchOutside(false);
        remind.setTitleGone(true);
        remind.setShowTxt("400-020-0018");
        remind.show();
    }*/

    public static String transDataStyle(String disclosure_date) {
        if(disclosure_date.contains("-")) {
            String[] split = disclosure_date.split("-");
            StringBuilder sb = new StringBuilder();

            for(int i = 0; i < split.length; ++i) {
                if(i == split.length - 1) {
                    sb.append(split[i]);
                } else {
                    sb.append(split[i] + ".");
                }
            }

            return sb.toString();
        } else {
            return disclosure_date;
        }
    }

    public static String transMonthStyle(String disclosure_date) {
        if(disclosure_date.contains("-")) {
            String[] split = disclosure_date.split("-");
            StringBuilder sb = new StringBuilder();

            for(int i = 1; i < split.length; ++i) {
                if(i == split.length - 1) {
                    sb.append(split[i]);
                } else {
                    sb.append(split[i] + ".");
                }
            }

            return sb.toString();
        } else {
            return "";
        }
    }

    @SuppressLint({"SimpleDateFormat"})
    public static String getCurrentTime() {
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }

    public static String getFormatDouble(Double num) {
        DecimalFormat fnum = new DecimalFormat("##0.00");
        String account = fnum.format(num);
        return account;
    }

    public static String getFormatFloat(Float num) {
        DecimalFormat fnum = new DecimalFormat("##0.00");
        String account = fnum.format(num);
        return account;
    }

    public static String getFormatData(String num) {
        if(num == null) {
            return "";
        } else if(num.length() < 6) {
            return num;
        } else {
            String temp = num.substring(0, 4);
            temp = temp + "-" + num.substring(4, 6) + "-";
            temp = temp + num.substring(6, num.length());
            return temp;
        }
    }

    public static byte[] bmpToByteArray(Bitmap bmp, boolean needRecycle) {
        int i;
        int j;
        if(bmp.getHeight() > bmp.getWidth()) {
            i = bmp.getWidth();
            j = bmp.getWidth();
        } else {
            i = bmp.getHeight();
            j = bmp.getHeight();
        }

        Bitmap localBitmap = Bitmap.createBitmap(i, j, Config.RGB_565);
        Canvas localCanvas = new Canvas(localBitmap);

        while(true) {
            localCanvas.drawBitmap(bmp, new Rect(0, 0, i, j), new Rect(0, 0, i, j), (Paint)null);
            if(needRecycle) {
                bmp.recycle();
            }

            ByteArrayOutputStream localByteArrayOutputStream = new ByteArrayOutputStream();
            localBitmap.compress(CompressFormat.JPEG, 100, localByteArrayOutputStream);
            localBitmap.recycle();
            byte[] arrayOfByte = localByteArrayOutputStream.toByteArray();

            try {
                localByteArrayOutputStream.close();
                return arrayOfByte;
            } catch (Exception var9) {
                i = bmp.getHeight();
                j = bmp.getHeight();
            }
        }
    }

    public static byte[] compressImage(Bitmap image) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(CompressFormat.JPEG, 100, baos);

        for(int options = 100; baos.toByteArray().length / 1024 > 32; options -= 10) {
            baos.reset();
            image.compress(CompressFormat.JPEG, options, baos);
        }

        return baos.toByteArray();
    }

    public static void recycleImageView(View view) {
        if(view != null) {
            if(view instanceof ImageView) {
                Drawable drawable = ((ImageView)view).getDrawable();
                if(drawable instanceof BitmapDrawable) {
                    Bitmap bmp = ((BitmapDrawable)drawable).getBitmap();
                    if(bmp != null && !bmp.isRecycled()) {
                        ((ImageView)view).setImageBitmap((Bitmap)null);
                        bmp.recycle();
                        bmp = null;
                    }
                }
            }

        }
    }

/*    public static String copyLogo() {
        Bitmap bmp = BitmapFactory.decodeResource(AppApplication.getContext().getResources(), R.drawable.app_logo);
        String filePath = com.jzkj.manage.cache.CacheManager.getInstance().getCachePath("applogo", 2);
        File SpicyDirectory = new File(filePath);
        if(!SpicyDirectory.exists()) {
            SpicyDirectory.mkdirs();
        }

        String filename = filePath + ".png";
        if(isSDExists(filename)) {
            return filename;
        } else {
            FileOutputStream out = null;

            try {
                out = new FileOutputStream(filename);
                bmp.compress(CompressFormat.PNG, 100, out);
            } catch (Exception var18) {
                filename = null;
                var18.printStackTrace();
            } finally {
                try {
                    out.flush();
                } catch (IOException var17) {
                    var17.printStackTrace();
                }

                try {
                    out.close();
                } catch (IOException var16) {
                    var16.printStackTrace();
                }

                out = null;
            }

            return filename;
        }
    }*/

    private static boolean isSDExists(String path) {
        try {
            File e = new File(path);
            return e.exists();
        } catch (Exception var2) {
            return false;
        }
    }

    public static boolean isValidTagAndAlias(String s) {
        Pattern p = Pattern.compile("^[\\u4E00-\\u9FA50-9a-zA-Z_@!#$&*+=.|￥¥]+$");
        Matcher m = p.matcher(s);
        return m.matches();
    }

    public static boolean isConnected(Context context) {
        ConnectivityManager conn = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = conn.getActiveNetworkInfo();
        return info != null && info.isConnected();
    }

    public static void showToast(final String toast, final Context context) {
        (new Thread(new Runnable() {
            public void run() {
                Looper.prepare();
                Toast.makeText(context, toast, Toast.LENGTH_SHORT).show();
                Looper.loop();
            }
        })).start();
    }

    public static String getStarAccount(String account) {
        String returnString = null;
        if(account.length() >= 11) {
            returnString = account.substring(0, 3) + getStar(account.length() - 7) + account.substring(account.length() - 4, account.length());
            return returnString;
        } else if(account.length() >= 6 && account.length() < 11) {
            returnString = account.substring(0, 2) + getStar(account.length() - 5) + account.substring(account.length() - 3, account.length());
            return returnString;
        } else if(account.length() > 4 && account.length() < 6) {
            returnString = account.substring(0, 1) + getStar(account.length() - 3) + account.substring(account.length() - 2, account.length());
            return returnString;
        } else {
            return account;
        }
    }

    public static String getStar(int num) {
        StringBuilder sb = new StringBuilder();

        for(int i = 0; i < num; ++i) {
            sb.append("*");
        }

        return sb.toString();
    }

    public static int getContextLength(String[] str, int a) {
        if(str != null && str.length != 0) {
            int length = 0;

            for(int i = 0; i < a; ++i) {
                length += str[i].length();
            }

            return length + a;
        } else {
            return 0;
        }
    }
}
